//获取应用实例
const app = getApp()
Page({
  data: {
    orderInfo: [],
    socketOpen: false
  },

  onLoad: function (options) {
    wx.showLoading({
      title: '加载中'
    });
    var that = this;
    
    if (app.globalData.phone == null) {
      var random = Math.floor(Math.random() * 100000);
      wx.connectSocket({
        url: 'ws://' + app.globalData.host + '/websocket/' + random
      })
    } else {
      wx.connectSocket({
        url: 'ws://' + app.globalData.host + '/websocket/' + app.globalData.phone
      })
    }
    
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开！')
      that.setData({
        socketOpen: true
      })
    })
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败，请检查！')
    })
    wx.request({
      url: 'http://' + app.globalData.host + '/unaccepted/orders',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      method: 'GET',
      success: function (res) {
        if (res.data.code == 1) {
          that.setData({
            orderInfo: res.data.data
          });
        }
        wx.hideLoading();
      }
    })
  },

  onReady: function () {
  },

  reLoadGetOrders: function () {
    wx.showLoading({
      title: '加载中'
    });
    var that = this;
    wx.request({
      url: 'http://' + app.globalData.host + '/unaccepted/orders',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      method: 'GET',
      success: function (res) {
        if (res.data.code == 1) {
          that.setData({
            orderInfo: res.data.data
          });
        }
        // 停止下拉动作
        wx.stopPullDownRefresh();
        wx.hideLoading();
        wx.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1000
        });
      }
    });
  },

  onShow: function () {
    var that = this;
    wx.onSocketMessage(function (res) {
      that.setData({
        receivedMessage: res.data
      });
      wx.showModal({
        title: '提示',
        content: '有订单发生变化，快看一下吧。',
        success: function (res) {
          if (res.confirm) {
            console.log('刷新');
            that.reLoadGetOrders();
          } else {
            console.log('刷新');
            that.reLoadGetOrders();
          }
        }
      })
    })
  },

  onHide: function () {
    
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

    wx.closeSocket();

    wx.onSocketClose(function (res) {
      console.log('WebSocket 已关闭！')
    });

    wx.onSocketError(function (res) {
      console.log('WebSocket连接关闭失败，请检查！')
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.reLoadGetOrders();
  },

  onReachBottom: function () {
  },

  makePhoneCall:function(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.text
    })
  },

  getOrders:function(e) {
    wx.vibrateShort({
      success: function() {
        console.log('开始抢单')
      }
    });
    if (app.globalData.sessionId == null) {
      wx.showModal({
        title: '请先登录',
        content: '你尚未登录，请登录后再操作',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.navigateTo({
              url: '/pages/user/login/login',
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      wx.request({
        url: 'http://' + app.globalData.host + '/accept/order',
        header: {
          'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        method: 'POST',
        data: {
          sessionId: app.globalData.sessionId,
          businessId: e.currentTarget.dataset.text
        },
        success:function(res) {
          if (res.data.code == 1) {
            wx.showToast({
              title: '抢单成功',
              icon: 'success',
              duration: 2000
            });
            // TODO 刷新当前页面 并 前往我的订单 
            
            wx.navigateTo({
              url: '../myOrders/myOrders',
            });
          } else if (res.data.code == 2) {
            wx.showToast({
              title: '禁止抢自己的订单',
              icon: 'none',
              duration: 2000
            });
          } else if (res.data.code == 3) {
            wx.showModal({
              title: '禁止抢单',
              content: res.data.msg,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                  wx.redirectTo({
                    url: '/pages/orders/myOrders/myOrders',
                  });
                } else if (res.cancel) {
                  wx.redirectTo({
                    url: './getOrders',
                  });
                }
              }
            })
          } else {

          }
        },
        fail:function() {
          wx.showToast({
            title: '抢单失败',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  }
});
